package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.BucketExistsArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.UploadObjectArgs;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioProperties minioProperties;

    @Override
    public String upload(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        String bucketName = minioProperties.getBucketName();

        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String nowStr = sdf.format(now);
        String fileName = nowStr + "_" + UUID.randomUUID().toString()+ "_" + file.getOriginalFilename();

        minioClient.putObject(PutObjectArgs.builder()
                        .bucket(bucketName)
                        // InputStream : 文件的输入流
                        // objectSize : 文件大小
                        // partSize : 分片大小
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .object(fileName)
                .build());
        // http://192.168.174.100:9000/lease/20221209123456_f0f0f0f0-f0f0-f0f0-f0f0-f0f0f0f0f0f0_1.jpg
        String url = minioProperties.getEndpoint() + "/" + bucketName +"/"+fileName;
        return url;
    }
}
